"""
工作流节点执行记录数据模型
"""
import os
from datetime import datetime, timezone
from zoneinfo import ZoneInfo
from sqlalchemy import Column, Integer, String, Text, DateTime, ForeignKey
from database import Base


class WorkflowNodeExecution(Base):
    """工作流节点执行记录表"""
    __tablename__ = "workflow_node_executions"

    id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    workflow_instance_id = Column(Integer, ForeignKey("workflow_instances.id"), nullable=False, index=True)
    node_id = Column(String(100), nullable=False, index=True)
    node_name = Column(String(255), nullable=False)
    node_type = Column(String(50), nullable=False)
    status = Column(String(50), nullable=False, index=True)  # 节点状态
    input_data = Column(Text, nullable=True)  # JSON 格式的输入数据
    output_data = Column(Text, nullable=True)  # JSON 格式的输出数据
    error_message = Column(Text, nullable=True)
    started_at = Column(DateTime(timezone=True), nullable=True)
    finished_at = Column(DateTime(timezone=True), nullable=True)
    duration = Column(Integer, nullable=True)  # 执行耗时(秒)
    retry_count = Column(Integer, nullable=False, default=0)

    # 异步执行新增字段
    external_task_id = Column(String(255), nullable=True)  # 外部任务ID
    submitted_at = Column(DateTime(timezone=True), nullable=True)  # 任务提交时间
    poll_count = Column(Integer, default=0)  # 轮询次数
    next_poll_at = Column(DateTime(timezone=True), nullable=True)  # 下次轮询时间
    poll_interval = Column(Integer, default=int(os.environ.get('POLL_INTERVAL_SECONDS', 300)))  # 轮询间隔(秒)，默认5分钟

    def __repr__(self):
        return f"<WorkflowNodeExecution(id={self.id}, node_id='{self.node_id}', status='{self.status}')>"
